<template>
  <div>
    <!-- 搜索栏 -->
    <!-- 查询结果栏 -->
    <el-card>
      <el-table :data="userList" style="width: 100%" height="250px">
        <el-table-column prop="userId" label="用户ID" width="120" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="role" label="用户角色" width="120" />
        <el-table-column prop="status" label="用户状态" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 1">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="openEditUi(scope.row.userId)" />
            <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteuser(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改密码 -->
    <el-row>
      <el-col :span="2" :offset="2">
        <div style="text-align: center;">
          <el-tag type="plain" style="font-size: 20px; background-color: transparent; color: black; border: none;">原密码
          </el-tag>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple-light">
          <el-input v-model="userpassword" placeholder="请输入原密码" show-password />
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="2" :offset="2">
        <div style="text-align: center;">
          <el-tag type="plain" style="font-size: 20px; background-color: transparent; color: black; border: none;">新密码
          </el-tag>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple-light">
          <el-input v-model="usernewpassword1" placeholder="请输入新密码" show-password />
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="2" :offset="2">
        <div style="text-align: center;">
          <el-tag type="plain" style="font-size: 20px; background-color: transparent; color: black; border: none;">新密码
          </el-tag>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple-light">
          <el-input v-model="usernewpassword2" placeholder="请输入新密码" show-password />
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="2" :offset="2">
        <el-button round @click="changePassword()">确定修改密码</el-button>
      </el-col>
    </el-row>

    <!-- 分页 -->

    <!-- 用户信息编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearform">
      <el-form ref="userFromRef" :model="userForm" :rules="rules">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="userForm.username" autocomplete="off" />
        </el-form-item>
        <!-- v-if="userForm.id == null || userForm.id == undefined" -->
        <!-- <el-form-item label="用户密码" prop="password" :label-width="formLabelWidth">
          <el-input v-model="userForm.password" type="password" autocomplete="off" />
        </el-form-item> -->
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="userForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <template>
            <el-select v-model="userForm.role" clearable placeholder="请选择用户角色">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-switch v-model="userForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="电子邮件" prop="email" :label-width="formLabelWidth">
          <el-input v-model="userForm.email" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/userManage'

export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'))
      }
      callback()
    }
    var checkUsername = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('用户名不能为空'))
      } else {
        // 去后端检查用户名使用数量
        userApi.checkUsernameCount(value).then((res) => {
          if (res.data === 1 && value !== this.userList[0].username) {
            return callback(new Error('用户名和他人不能重复'))
          }
          if (res.data > 1) {
            return callback(new Error('数据库用户名不唯一了，快修bug'))
          }
          return callback()
        })
      }
    }
    return {
      options: [{
        value: '普通用户',
        label: '普通用户'
        // }, {
        //   value: '管理员',
        //   label: '管理员'
      }],
      value: '',
      formLabelWidth: '130px',
      userForm: {},
      userpassword: '',
      usernewpassword1: '',
      usernewpassword2: '',
      dialogFormVisible: false,
      title: '',
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10
      },
      userList: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户初始密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户电子邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }

        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {

    changePassword() {
      if (this.usernewpassword1 !== this.usernewpassword2) {
        alert('两次密码不一致')
      } else {
        userApi.checkPassword(this.userList[0].userId, this.userpassword)
          .then(response => {
            if (response.data === true) {
              console.log('true')
              this.userList[0].password = this.usernewpassword1
              userApi.saveUser(this.userList[0])
                .then(() => {
                  alert('密码修改成功')
                  // 这里可以根据需求进行页面跳转或其他操作
                })
                .catch(error => {
                  console.error('保存用户信息失败：', error)
                  alert('保存用户信息失败，请重试')
                })
            } else if (response.data === false) {
              alert('原密码错误')
            }
          })
          .catch(error => {
            console.error('检查密码失败：', error)
            alert('出现错误，请重试')
          })
      }
    },
    deleteuser(user) {
      this.$confirm(`用户${user.username}，您确定要注销吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.deleteById(user.userId).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消注销'
        })
      })
    },
    saveUser() {
      // 触发表单验证
      this.$refs.userFromRef.validate((valid) => {
        if (valid) {
          // 提交请求到后台
          userApi.saveUser(this.userForm).then(response => {
            // 成功提交的提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            // 刷新数据
            this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 清除表单报错信息
    clearform() {
      this.userForm = {}
      this.$refs.userFromRef.clearValidate()
    },
    openEditUi(userId) {
      this.title = '修改用户'
      // 根据id查数据
      userApi.getUserById(userId).then(response => {
        this.userForm = response.data
      })
      this.dialogFormVisible = true
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getUserList()
    },
    getUserList() {
      this.searchModel.username = this.$store.state.user.username
      userApi.getUserList(this.searchModel).then(response => {
        this.userList = response.data.rows
        this.total = response.data.total
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

#search .el-input {
  width: 200px;
  margin-right: 10px;
}

.el-dialog .el-input {
  width: 200px;

}
</style>
